import tableFun from '@/components/base/grid/configs/modules/func';
import Vue from 'vue';
import XEUtils from 'xe-utils';

function getFormatter(
  config: any,
  options?: {
    isParams?: boolean;
    option?: any;
    isSlider?: boolean;
  }
) {
  const formatterType = config.type;
  let formatter = null;

  if (['number', 'currency', 'percent'].indexOf(formatterType) > -1) {
    formatter = (v: any) => {
      if (options && options.isParams) v = v.value[v.dimensionNames[0]];
      if (options && options.isSlider && options.option)
        v =
          options.option.dataset.source[v][
            options.option.dataset.dimensions[0]
          ];
      return tableFun.numberFormatter(v, config);
    };
  } else if (formatterType === 'i18n') {
    formatter = (v: any) => {
      if (options && options.isParams) v = v.value[v.dimensionNames[0]];
      if (options && options.isSlider && options.option)
        v =
          options.option.dataset.source[v][
            options.option.dataset.dimensions[0]
          ];
      return Vue.prototype.$srv.getI18nBySrv(v);
    };
  } else if (['date', 'time', 'datetime'].indexOf(formatterType) > -1) {
    if (formatterType === 'date')
      formatter = (v: any) => {
        if (options && options.isParams) v = v.value[v.dimensionNames[0]];
        if (options && options.isSlider && options.option)
          v =
            options.option.dataset.source[v][
              options.option.dataset.dimensions[0]
            ];
        return tableFun.timeFormatter(v, 'yyyy-MM-dd', formatterType);
      };
    else if (formatterType === 'datetime')
      formatter = v => {
        if (options && options.isParams) v = v.value[v.dimensionNames[0]];
        if (options && options.isSlider && options.option)
          v =
            options.option.dataset.source[v][
              options.option.dataset.dimensions[0]
            ];
        return tableFun.timeFormatter(
          v,
          'yyyy-MM-dd HH:mm:ss.SSS',
          formatterType
        );
      };
    else if (formatterType === 'time')
      formatter = v => {
        if (options && options.isParams) v = v.value[v.dimensionNames[0]];
        if (options && options.isSlider && options.option)
          v =
            options.option.dataset.source[v][
              options.option.dataset.dimensions[0]
            ];
        return tableFun.timeFormatter(v, 'HH:mm:ss.SSS', formatterType);
      };
  } else if (formatterType === 'custom') {
    formatter = v => {
      if (options && options.isParams) v = v.value[v.dimensionNames[0]];
      if (options && options.isSlider && options.option)
        v =
          options.option.dataset.source[v][
            options.option.dataset.dimensions[0]
          ];
      return tableFun.numberFormatter(v, config) + config.custom;
    };
  }
  return formatter;
}

function getAxisConfig(xy: string, config: any) {
  const axisOptionArr = [];
  config.forEach((el: any, idx: number) => {
    const axisOption = {
      show: true,
      type: '',
      axisLabel: {},
      axisLine: {
        show: !(xy === 'x' && idx === 1)
      },
      axisTick: {
        show: true
      }
    };
    if (el.series.type === 'pie') {
      axisOption.show = false;
    }
    if (el.axis) {
      const o = el.axis[xy];
      axisOption.type = o.type;
      if (o.name && o.name !== '') axisOption['name'] = o.name;
      if (o.min && o.min !== '') axisOption['min'] = XEUtils.toNumber(o.min);
      if (o.max && o.max !== '') axisOption['max'] = XEUtils.toNumber(o.max);
      if (o.interval && o.interval !== '')
        axisOption['interval'] = XEUtils.toNumber(o.interval);
      if (o.scale) axisOption['scale'] = o.scale;
      if (!XEUtils.isEmpty(o.formatter))
        axisOption.axisLabel['formatter'] = getFormatter(o.formatter);
    }
    axisOptionArr.push(axisOption);
  });

  return axisOptionArr;
}

function getDimensions(x: any[], y: any[], option: any) {
  let dimensions = [];
  const xx = x.map(el => el.field);
  const yy = y.map(el => el.field);
  if (option.xAxis[0].type === 'category') {
    dimensions = dimensions.concat(xx, yy);
  } else if (option.yAxis[0].type === 'category') {
    dimensions = dimensions.concat(yy, xx);
  }
  return dimensions;
}

function getSeries(config: any[]) {
  const series = [];
  config.forEach(el => {
    const c = el.series;
    const a = {
      type: c.type,
      label: {
        show: false,
        position: 'inside'
      },
      itemStyle: {}
    };
    switch (a.type) {
      case 'bar':
        a.label.show = true;
        break;
      case 'pie':
        a.label.show = true;
        a.label.position = 'outside';
        if (!XEUtils.isEmpty(el.axis.x.formatter))
          a.label['formatter'] = getFormatter(el.axis.x.formatter, {
            isParams: true
          });
        a['emphasis'] = {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        };
        break;
      case 'line':
        a.label.show = true;
        break;
      default:
        throw new Error(`err`);
    }
    if (c.smooth) a['smooth'] = c.smooth;
    if (c.stack && c.stack !== '') a['stack'] = c.stack;
    if (c.radius && (c.radius[0] !== '' || c.radius[1] !== ''))
      a['radius'] = [`${c.radius[0]}%`, `${c.radius[1]}%`];
    if (c.style && c.style.itemColor) a.itemStyle['color'] = c.style.itemColor;
    if (c.style && c.style.hasArea) a['areaStyle'] = {};
    a['yAxisIndex'] = XEUtils.toNumber(c.yIndex);
    series.push(a);
  });
  return series;
}

function getTitle(config: any) {
  const a = {
    left: 'center',
    align: 'right'
  };
  const b = config.title;
  if (b) {
    if (b.text && b.text !== '') a['text'] = b['text'];
    if (b.subtext && b.subtext !== '') a['subtext'] = b['subtext'];
  }

  return a;
}

function getOption(x: any[], y: any[], gridConfig: any, dataConfig: any[]) {
  const option: any = {
    title: getTitle(gridConfig),
    legend: {
      type: 'scroll',
      orient: dataConfig[0].series.type === 'pie' ? 'vertical' : 'horizontal',
      right: 10,
      top: 0,
      // bottom: 20,
      formatter: (name: any) => {
        return Vue.prototype.$srv.getI18nBySrv(name);
      }
    },
    dataZoom: [
      {
        show: false,
        type: 'slider',
        bottom: '10',
        start: 0,
        end: 100,
        labelFormatter: null
      }
    ],
    grid: {},
    tooltip: {},
    dataset: {
      dimensions: [],
      source: []
    },
    xAxis: getAxisConfig('x', dataConfig),
    yAxis: getAxisConfig('y', dataConfig),
    series: getSeries(dataConfig)
  };

  option.dataset.dimensions = getDimensions(x, y, option);

  // option.series = getSeries(dataConfig);

  if (gridConfig.slider.show === true) {
    option.dataZoom[0].show = true;
    option.dataZoom[0].start = gridConfig.slider.start;
    option.dataZoom[0].end = gridConfig.slider.end;
    if (!XEUtils.isEmpty(dataConfig[0].axis.x.formatter))
      option.dataZoom[0].labelFormatter = getFormatter(
        dataConfig[0].axis.x.formatter,
        {
          option,
          isSlider: true
        }
      );
  } else {
    option.grid['bottom'] = 30;
  }
  return option;
}

export { getOption };
